use std::collections::HashSet;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = sessionStorage)]
    fn setItem(key: &str, value: &str);

    #[wasm_bindgen(js_namespace = sessionStorage)]
    fn getItem(key: &str) -> Option<String>;

    #[wasm_bindgen(js_namespace = sessionStorage)]
    fn removeItem(key: &str);
}

/// SessionManager provides utilities for managing session storage in WebAssembly
pub struct SessionManager;

impl SessionManager {
    const EXPANDED_MENUS_KEY: &'static str = "r2mo_expanded_menus";

    /// Save the set of expanded menu IDs to session storage
    pub fn save_expanded_menus(menus: &HashSet<String>) {
        if menus.is_empty() {
            removeItem(Self::EXPANDED_MENUS_KEY);
            return;
        }

        match serde_json::to_string(menus) {
            Ok(json) => {
                setItem(Self::EXPANDED_MENUS_KEY, &json);
            }
            Err(_) => {
                // 如果序列化失败，就清除存储
                removeItem(Self::EXPANDED_MENUS_KEY);
            }
        }
    }

    /// Load the set of expanded menu IDs from session storage
    pub fn load_expanded_menus() -> HashSet<String> {
        match getItem(Self::EXPANDED_MENUS_KEY) {
            Some(json) => serde_json::from_str(&json).unwrap_or_default(),
            None => HashSet::new(),
        }
    }

    /// Clear the stored expanded menus
    pub fn clear_expanded_menus() {
        removeItem(Self::EXPANDED_MENUS_KEY);
    }
}
